<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>帮助</title>
  <link rel="icon" href="http://om87tl0nf.bkt.clouddn.com/ico.ico" type="image/x-icon">
  <link rel="stylesheet" href="./css/common.css">
  <link rel="stylesheet" href="./css/help.css">
</head>
<body>
  <header class="header">
    <div class="header-wrapper">
      <div class="column">
        <img class="logo" src="http://our8pafcg.bkt.clouddn.com/zhike/images/logo.png" alt="智客">
      </div>
      <div class="column column-right">
        <a href="/">首页</a>
        <a id="study_id" href="/study">开始研究</a>
        <a id="personal_center_id" href="/personal_center">个人中心</a>
        <a id="help_id" href="/help" class="active-tab">帮助</a>
        <button class="btn btn-default btn-radius" id="logout">退出登录</button>
      </div>
    </div>
  </header>
  <div class="container">
    <ul class="nav">
      <li class="list-h1 active">
        <a class="nav-item" href="#start-study">开始研究</a>
      </li>
    </ul>
    <div class="content">
      <h1 id="start-study">开始研究</h1>
      <p>为了让策略运行，需要编写两个函数：</p>
      <pre>
def init():
  ch=ContextHost(datalist[-300:])  #300为需要回测的bar个数
  ch.spread=0.3#点差，默认为0.3
  ch.leverage=10 #杠杆，默认10倍
  ch.calcgap=5 #每次run策略需要用到的历史数据个数，默认为5
  ch.doLoop(run)

def run(context):
  opsize=20.0
  opsize=context.maxbuy()  # context.maxbuy()为订单最大可下的手数
  if context.data[-1]["Close"] &gt; context.data[-1]["wma"]:
    context.buy(opsize,context.data[-1]["Close"]-10,context.data[-1]["Close"]+60)
  if context.data[-1]["Close"] &lt; context.data[-1]["wma"]:
    context.buy(opsize,context.data[-1]["Close"]-10,context.data[-1]["Close"]+60)
      </pre>
      <ol>
        <li>
          <p>此策略为当收盘价大于移动平均值，即下一个多单，手数为20，止盈60美元，止损10美元，产品为黄金。
            用户可根据自己的算法自定义策略。</p>
        </li>
        <li>
          <p>
            <i>context.data</i> 为 <i>init</i> 定义的回测数据，[-1] 表示最新数据，[-2] 表示上一个数据，以此类推。
          </p>
        </li>
        <li>
          <p>
            回测为从第 <i>calcgap</i> 个数据开始往后，每次运行 <i>run</i>判断是否符合开仓平仓条件，
            最终得出策略回测效果。
          </p>
        </li>
        <li>
          <p><i>sklearn</i>，<i>tilab</i>，<i>TensorFlow</i>等相关库都已经安装，可自行调用。</p>
        </li>
      </ol>

      <h1 id="start-study">策略实例１</h1>
      <p>本实例中，先列出整个模拟函数。然后将各部分代码分块列出。</p>
      <p>模拟函数：</p>
      <pre>
#==========================================
# First,  you need to define the PARAMETERS
#==========================================
#---------------------------------------------
# Setting the value of the parameter blance, 
# which is the inital capital.
blance = 60000
#----------------------------------------------------------------
# setting the value of the parameter calcgap, which is the number 
# of historical data you need for the strategy to learn:
calcgap = 5
#----------------------------
# Setting the value of a, 
# which denotes the parameter 
# related to the opsize. 
a = 6
#----------------------------------
# Setting the value of the stopearn 
# /takeprofit and stoploss: 
stopearn = 60
stoploss = 55

#====================================
# Here we define the class ContextHost
#====================================
class ContextHost(object):
    class Context(object):
        def __init__(self,data):
            self.data=data
        def maxbuy(self):
            return self.host.blance/self.data[-1]["Close"] - 0.0001
        def buy(self,amont,stoploss,stopearn):
            if self.host.blance &gt= self.data[-1]["Close"]*amont:
                self.host.litera.append({
                    "time":self.data[-1]["Date"],
                    "type":1,
                    "prise":self.data[-1]["Close"],
                    "amont":amont,
                    "range":[stoploss,stopearn]
                })
                mkprice=self.data[-1]["Close"]*amont
                self.host.blance-=mkprice
        def litera(self):
            return self.host.litera
    def __init__(self,data,blance=blance):
        self.calcgap=calcgap
        self.data=data
        self.litera=[]
        self.closelitera=[]
        self.marketvalue=[]
        self.blance=blance
    def doLoop(self,fun):
        for i in xrange(self.calcgap,len(self.data)):
            dline=self.data[i]
            for j in self.litera[:]:
                if j["range"][0] &gt dline["Low"] :
                    j["close_prise"]=j["range"][0]
                    j["close_time"]=dline["Date"]
                    self.blance+=j["close_prise"]*j["amont"]
                    self.closelitera.append(j)
                    self.litera.remove(j)
                elif j["range"][1] &lt dline["High"]:
                    j["close_prise"]=j["range"][1]
                    j["close_time"]=dline["Date"]
                    self.blance+=j["close_prise"]*j["amont"]
                    self.closelitera.append(j)
                    self.litera.remove(j)
            now_mp=0
            for j in self.litera:
                if j["type"]==1:
                    now_mp+=dline['Close']*j["amont"]
            self.marketvalue.append(now_mp+self.blance)
            dline["mv"]=now_mp+self.blance
            ctx=ContextHost.Context(self.data[i-self.calcgap:i])
            ctx.host=self
            fun(ctx)

with open("/root/data/goldDI.svc", 'rb') as fid:
    svc=cPickle.load(fid)

def run(context):
    dline=train_svc.getone(context.data[-1])
    line=np.array([dline,])
    sres=svc.decision_function(line)
    context.data[-1]["svc"]=sres[0]
    allweight=0
    allsumsvc=0
    for i in xrange(len(context.data)):
        allweight+=i+1
        if "svc" not in context.data[i]:
            break
        allsumsvc+=context.data[i]["svc"]*(i+1)
    if allweight==0:
        return
    wsvc=allsumsvc/allweight

    #======================================
    #save the data: DO NOT CHANGE this part
    #======================================
    file_o = open(name0, 'a')
    file_o.write("{0:25s} {1:13s}\n".format("In simulation, wsvc is:",str(wsvc)))
    file_o.close()
    
    #=================
    #the main strategy
    #=================
    context.data[-1]["wsvc"]=wsvc
    if "wsvc" in context.data[-2]:
        if wsvc &gt 5 and context.data[-2]["wsvc"] &gt wsvc:
            context.buy(min(context.maxbuy(), a ),context.data[-1]["Close"]- stoploss, context.data[-1]["Close"]+ stopearn )

def getv(one,key):
    if key in one:
        return one[key]
    else:
        return float("NaN")
if __name__ == "__main__":
    name0 = "result0.dat"
    datalist=fetchdata.loaddate("/root/data/golddata.gz")
    ch=ContextHost(datalist[-360:])
    ch.doLoop(run)
    file_o = open(name0, 'a')
    file_o.write("[")
    for i in range(len(ch.marketvalue)-1):
        file_o.write("{0:10s},".format(str(ch.marketvalue[i])))
    file_o.write("{0:10s}".format(str(ch.marketvalue[len(ch.marketvalue)-1])))
    file_o.close()
    print open(name0,'r').read()
      </pre>
      <p>(1)设置参数</p>
      <pre>
#========================
#To define the PARAMETERS
#========================
blance = 60000
calcgap = 5
a = 6
stopearn = 60
stoploss = 55
      </pre>
      <p>(2)定义类</p>
      <pre>
#===============================
#To define the class ContextHost
#===============================
class ContextHost(object):
    class Context(object):
        def __init__(self,data):
            self.data=data
        def maxbuy(self):
            return self.host.blance/self.data[-1]["Close"] - 0.0001
        def buy(self,amont,stoploss,stopearn):
            if self.host.blance &gt= self.data[-1]["Close"]*amont:
                self.host.litera.append({
                    "time":self.data[-1]["Date"],
                    "type":1,
                    "prise":self.data[-1]["Close"],
                    "amont":amont,
                    "range":[stoploss,stopearn]
                })
                mkprice=self.data[-1]["Close"]*amont
                self.host.blance-=mkprice
        def litera(self):
            return self.host.litera
    def __init__(self,data,blance=blance):
        self.calcgap=calcgap
        self.data=data
        self.litera=[]
        self.closelitera=[]
        self.marketvalue=[]
        self.blance=blance
    def doLoop(self,fun):
        for i in xrange(self.calcgap,len(self.data)):
            dline=self.data[i]
            for j in self.litera[:]:
                if j["range"][0] &gt dline["Low"] :
                    j["close_prise"]=j["range"][0]
                    j["close_time"]=dline["Date"]
                    self.blance+=j["close_prise"]*j["amont"]
                    self.closelitera.append(j)
                    self.litera.remove(j)
                elif j["range"][1] &lt dline["High"]:
                    j["close_prise"]=j["range"][1]
                    j["close_time"]=dline["Date"]
                    self.blance+=j["close_prise"]*j["amont"]
                    self.closelitera.append(j)
                    self.litera.remove(j)
            now_mp=0
            for j in self.litera:
                if j["type"]==1:
                    now_mp+=dline['Close']*j["amont"]
            self.marketvalue.append(now_mp+self.blance)
            dline["mv"]=now_mp+self.blance
            ctx=ContextHost.Context(self.data[i-self.calcgap:i])
            ctx.host=self
            fun(ctx)
      </pre>
      <p>(3)获取源数据</p>
      <pre>
with open("/root/data/goldDI.svc", 'rb') as fid:
    svc=cPickle.load(fid)
      </pre>
      <p>(4)构造run()函数</p>
      <pre>
def run(context):
    dline=train_svc.getone(context.data[-1])
    line=np.array([dline,])
    sres=svc.decision_function(line)
    context.data[-1]["svc"]=sres[0]
    allweight=0
    allsumsvc=0
    for i in xrange(len(context.data)):
        allweight+=i+1
        if "svc" not in context.data[i]:
            break
        allsumsvc+=context.data[i]["svc"]*(i+1)
    if allweight==0:
        return
    wsvc=allsumsvc/allweight

    #======================================
    #save the data: DO NOT CHANGE this part
    #======================================
    file_o = open(name0, 'a')
    file_o.write("{0:25s} {1:13s}\n".format("In simulation, wsvc is:",str(wsvc)))
    file_o.close()
    
    #=================
    #the main strategy
    #=================
    context.data[-1]["wsvc"]=wsvc
    if "wsvc" in context.data[-2]:
        if wsvc &gt 5 and context.data[-2]["wsvc"] &gt wsvc:
            context.buy(min(context.maxbuy(), a ),context.data[-1]["Close"]- stoploss, context.data[-1]["Close"]+ stopearn )

def getv(one,key):
    if key in one:
        return one[key]
    else:
        return float("NaN")

if __name__ == "__main__":
    name0 = "result0.dat"
    datalist=fetchdata.loaddate("/root/data/golddata.gz")
    ch=ContextHost(datalist[-360:])
    ch.doLoop(run)
    file_o = open(name0, 'a')
    file_o.write("[")
    for i in range(len(ch.marketvalue)-1):
        file_o.write("{0:10s},".format(str(ch.marketvalue[i])))
    file_o.write("{0:10s}".format(str(ch.marketvalue[len(ch.marketvalue)-1])))
    file_o.close()
    print open(name0,'r').read()
      </pre>
      <ol>
        <li>
          <p>可将这段代码复制到“开始研究”页面的代码框中，点击"运行"按钮，就可看到该策略的运行的结果及其动态图像。代码第(1)部分是一些可以改动的参数，用户可自定义这些参数。</p>
　　　　　<p>参数如下：
　　　　　　<ol>
              <li>stoploss: 止损</li>
              <li>stopearn: 止盈</li>
              <li>blance: 初始资金</li>
              <li>calcgap: 需要用于机器学习算法的历史数据的个数。程序运行时，最开始calcgap个数据点不做买或卖的操作。</li>
            </ol>
　　　　　</p>
        </li>
      </ol>
    </div>
  </div>

<script src="/js/jquery.js"></script>
<!--For logout-->
<script src="/js/validation_logout.js"></script>

</body>
</html>
